#include "game_server.hpp"
#include "protocol_handler.hpp"
#include <iostream>

GameServer::GameServer(boost::asio::io_context& io_context, 
                      const std::string& address, 
                      unsigned short port)
    : io_context_(io_context) {
    websocket_server_ = std::make_unique<WebSocketServer>(io_context, address, port, *this);
    message_handler_ = std::make_unique<MessageHandler>();
}

void GameServer::start() {
    websocket_server_->start();
    Logger::info("Game server started");
}

void GameServer::stop() {
    websocket_server_->stop();
    Logger::info("Game server stopped");
}

void GameServer::handle_message(const std::vector<uint8_t>& data, uint32_t session_id) {
    try {
        // 将二进制数据转换为JSON
        std::string json_str(data.begin(), data.end());
        auto message = nlohmann::json::parse(json_str);

        // 打印消息
        Logger::info("Received message: {}", message.dump(4));
        
        // 使用消息处理器处理消息
        message_handler_->handle_message(*this, message, session_id);
    } catch (const std::exception& e) {
        Logger::error("Error processing message for session {}: {}", session_id, e.what());
    }
}

void GameServer::register_protocol(const std::string& protocol_name, std::shared_ptr<IProtocolHandler> protocol) {
    message_handler_->register_protocol(protocol_name, protocol);
}

void GameServer::send_message(uint32_t session_id, const nlohmann::json& message) {
    websocket_server_->send_message(session_id, message);
}

// void GameServer::handle_new_connection(std::shared_ptr<TcpSession> session) {
//     Logger::info("New connection established, session ID: {}", session->get_session_id());
// }

// void GameServer::handle_session_closed(uint32_t session_id) {
//     Logger::info("Session closed: {}", session_id);
// }